package 回溯算法;

public class exist79 {
    boolean flag = false;
    int[] dx = {1, 0, -1, 0};
    int[] dy = {0, 1, 0, -1};
    boolean[][] vis;
    private int len;
    private int row;

    public boolean exist(char[][] board, String word) {
        len = board.length;
        if (len <= 0) {
            return flag;
        }
        row = board[0].length;
        vis = new boolean[len][row];
        for (int i = 0; i < len; i++) {
            for (int j = 0; j < row; j++) {
                dfs(board, i, j, word, 0, vis);
            }
        }
        return flag;
    }

    private void dfs(char[][] board, int x, int y, String word, int index, boolean[][] vis) {
        if (word.length() == index) {
            flag = true;
            return;
        }
        if (x < 0 || x >= len || y < 0 || y >= row || word.charAt(index) != board[x][y] || vis[x][y]) {
            return;
        }
        vis[x][y] = true;
        for (int i = 0; i < 4; i++) {
            int xx = dx[i] + x;
            int yy = dy[i] + y;
            dfs(board, xx, yy, word, index + 1, vis);
        }
        vis[x][y] = false;
    }
}
